# from skimage import data,color,io
# from matplotlib import pyplot as plt
# import numpy as np
# image = io.imread('lena.bmp')
# # 将lena图像转换为灰度图像
# gray_img = color.rgb2gray(image)
# plt.figure()  # 创建新的图像窗口
# plt.imshow(gray_img, 'gray'), 

# plt.show()
# # 将图像转换为NumPy数组
# image_array = np.array(image)

# # 获取图像数组的形状和维度
# shape = image_array.shape
# dimensions = image_array.ndim

# print("图像数组的形状:", shape)
# print("图像的维度:", dimensions)


################
# from skimage import data, color, io, exposure
# from matplotlib import pyplot as plt
# import numpy as np

# def set_ch():
#     from pylab import mpl
#     mpl.rcParams['font.sans-serif']=['FangSong']
#     mpl.rcParams['axes.unicode_minus']=False
# set_ch()

# # 读取图像
# image = io.imread('pout.tif')

# # 检查图像的通道数
# if image.ndim == 2:
#     # 图像已经是灰度图像
#     gray_img = image
# else:
#     # 图像是彩色图像，需要转换为灰度图像
#     gray_img = color.rgb2gray(image)

# # 进行直方图均衡化
# equalized_image = exposure.equalize_hist(gray_img)

# # 显示原始图像和均衡化后的图像
# plt.figure(figsize=(10, 5))

# plt.subplot(1, 2, 1)
# plt.title('原始图像')
# plt.imshow(gray_img, cmap='gray')
# plt.axis('off')

# plt.subplot(1, 2, 2)
# plt.title('均衡化后的图像')
# plt.imshow(equalized_image, cmap='gray')
# plt.axis('off')

# plt.show()

# # 计算均衡化后图像的直方图
# if equalized_image.dtype == np.uint8:  # 如果图像是8位灰度图像
#     hist_eq, bins_eq = np.histogram(equalized_image.flatten(), bins=256, range=[0, 256])
# else:  # 如果图像是浮点灰度图像（例如0到1之间）
#     hist_eq, bins_eq = np.histogram(equalized_image.flatten(), bins=256, range=[0, 1])

# # 显示均衡化后的直方图
# plt.figure()  # 创建新的图像窗口
# plt.title("均衡化后的灰度图像直方图")
# plt.xlabel("灰度值")
# plt.ylabel("像素数量")
# plt.plot(bins_eq[:-1], hist_eq)
# plt.xlim([0, 256 if equalized_image.dtype == np.uint8 else 1])
# plt.show()


############
# from skimage import data, io, color
# from matplotlib import pyplot as plt
# import numpy as np

# plt.rcParams['font.sans-serif'] = ['SimHei'] 
# plt.rcParams['axes.unicode_minus'] = False

# # 读取图像
# image = io.imread(r'c:\Users\HP\Desktop\python\chapter02\flower.jpg')

# # 检查图像是否成功读取
# if image is None:
#     print("图像读取失败，请检查文件路径")
# else:
#     # 分离R、G、B分量
#     imageR = np.zeros_like(image)
#     imageR[:, :, 0] = image[:, :, 0]  # 设置R通道

#     imageG = np.zeros_like(image)
#     imageG[:, :, 1] = image[:, :, 1]  # 设置G通道

#     imageB = np.zeros_like(image)
#     imageB[:, :, 2] = image[:, :, 2]  # 设置B通道

#     # 将RGB图像转换为HSV图像
#     imageHSV = color.rgb2hsv(image)

#     # 分离H、S、V分量
#     imageH = np.zeros_like(imageHSV)
#     imageH[:, :, 0] = imageHSV[:, :, 0]  # 设置H通道

#     imageS = np.zeros_like(imageHSV)
#     imageS[:, :, 1] = imageHSV[:, :, 1]  # 设置S通道

#     imageV = np.zeros_like(imageHSV)
#     imageV[:, :, 2] = imageHSV[:, :, 2]  # 设置V通道

#     # 创建一个包含七个子图的窗体
#     fig, axs = plt.subplots(3, 3, figsize=(15, 15))

#     # 显示原始图像
#     axs[0, 0].imshow(image)
#     axs[0, 0].set_title('RGB图像')
#     axs[0, 0].axis('off')

#     # 显示R分量
#     axs[0, 1].imshow(imageR)
#     axs[0, 1].set_title('R通道图像')
#     axs[0, 1].axis('off')

#     # 显示G分量
#     axs[0, 2].imshow(imageG)
#     axs[0, 2].set_title('G通道图像')
#     axs[0, 2].axis('off')

#     # 显示B分量
#     axs[1, 0].imshow(imageB)
#     axs[1, 0].set_title('B通道图像')
#     axs[1, 0].axis('off')

#     # 显示H分量
#     axs[1, 1].imshow(imageH)
#     axs[1, 1].set_title('H通道图像')
#     axs[1, 1].axis('off')

#     # 显示S分量
#     axs[1, 2].imshow(imageS)
#     axs[1, 2].set_title('S通道图像')
#     axs[1, 2].axis('off')

#     # 显示V分量
#     axs[2, 0].imshow(imageV)
#     axs[2, 0].set_title('V通道图像')
#     axs[2, 0].axis('off')

#     # 空白子图
#     axs[2, 1].axis('off')
#     axs[2, 2].axis('off')

#     # 显示窗体
#     plt.tight_layout()
#     plt.show()
# from skimage import data, io, color
# from matplotlib import pyplot as plt
# import numpy as np

# plt.rcParams['font.sans-serif'] = ['SimHei'] 
# plt.rcParams['axes.unicode_minus'] = False

# # 读取图像
# image = io.imread(r'c:\Users\HP\Desktop\python\chapter02\flower.jpg')

# # 检查图像是否成功读取
# if image is None:
#     print("图像读取失败，请检查文件路径")
# else:
#     # 将RGB图像转换为HSV图像
#     imageHSV = color.rgb2hsv(image)

#     # 调整H、S、V分量
#     imageHSV[:, :, 0] = np.clip(imageHSV[:, :, 0] * 0.8, 0, 1)  # H分量乘以0.8
#     imageHSV[:, :, 1] = np.clip(imageHSV[:, :, 1] * 1.3, 0, 1)  # S分量乘以1.3
#     imageHSV[:, :, 2] = np.clip(imageHSV[:, :, 2] * 1.2, 0, 1)  # V分量乘以1.2

#     # 将调整后的HSV图像转换回RGB图像
#     adjusted_image = color.hsv2rgb(imageHSV)

#     # 创建一个包含两个子图的窗体
#     fig, axs = plt.subplots(1, 2, figsize=(10, 5))

#     # 显示原始图像
#     axs[0].imshow(image)
#     axs[0].set_title('原始RGB图像')
#     axs[0].axis('off')

#     # 显示调整后的图像
#     axs[1].imshow(adjusted_image)
#     axs[1].set_title('调整后的RGB图像')
#     axs[1].axis('off')

#     # 显示窗体
#     plt.tight_layout()
#     plt.show()

##############3
# import matplotlib.pyplot as plt
# import matplotlib.image as io
# import numpy as np
# plt.rcParams['font.sans-serif'] = ['SimHei'] 
# plt.rcParams['axes.unicode_minus'] = False
# # 读取图像
# image = io.imread('pout.tif')

# # 检查图像是否成功读取
# if image is None:
#     print("图像读取失败，请检查文件路径")
# else:
#     # 创建一个包含四个子图的窗体
#     fig, axs = plt.subplots(1, 4, figsize=(20, 5))

#     # 显示原图
#     axs[0].imshow(image, cmap='gray')
#     axs[0].set_title('原图')
#     axs[0].axis('off')

#     # 进行幂次变换并显示结果
#     gammas = [0.3, 0.6, 0.8]
#     for i, gamma in enumerate(gammas):
#         # 幂次变换
#         transformed_image = np.power(image, gamma)
#         # 显示变换后的图像
#         axs[i + 1].imshow(transformed_image, cmap='gray')
#         axs[i + 1].set_title(f'{gamma}gama变换')
#         axs[i + 1].axis('off')

#     # 显示窗体
#     plt.show()

################
# import matplotlib.pyplot as plt
# import matplotlib.image as mpimg
# plt.rcParams['font.sans-serif'] = ['SimHei'] 
# plt.rcParams['axes.unicode_minus'] = False
# # 读取图像
# image = mpimg.imread('lenagray.jpg')

# # 获取图像数组的形状和维度
# shape = image.shape
# dimensions = image.ndim

# # 打印图像数组的形状和维度
# print("图像数组的形状:", shape)
# print("图像的维度:", dimensions)

# # 裁剪图像
# cropped_image = image[10:150, 20:170]

# # 显示裁剪后的图像
# plt.imshow(cropped_image, cmap='gray')
# plt.title('裁剪后的图像')
# plt.axis('off')
# plt.show()
################
# from skimage import data, color, io
# from matplotlib import pyplot as plt
# import numpy as np

# # 定义灰度级到彩色变换    
# L = 255    

# def GetR(gray):
#     if gray < 64:
#         return 0
#     elif 64 <= gray < 256:
#         if 64 <= gray < 128:
#             return 0
#         elif 128 <= gray < 192:
#             return 4 * (gray - 128)
#         else:
#             return 255
#     return 0

# def GetG(gray):
#     if gray < 64:
#         return 4 * gray
#     elif 64 <= gray < 128:
#         return 255
#     elif 128 <= gray < 192:
#         return 255
#     else:
#         return 1023 - 4 * (gray - 192)

# def GetB(gray):
#     if gray < 64:
#         return 255
#     elif 64 <= gray < 128:
#         return 1023 - 4 * (gray - 64)
#     elif 128 <= gray < 192:
#         return 0
#     else:
#         return 0

# # 加载并转换为灰度图像
# image = io.imread('test.jpg')
# gray_image = color.rgb2gray(image) * L  # 将灰度值调整到0-255之间

# # 创建空的RGB图像数组
# height, width = gray_image.shape
# pseudo_color_image = np.zeros((height, width, 3), dtype=np.uint8)

# # 遍历每个像素并应用颜色映射
# for i in range(height):
#     for j in range(width):
#         gray = int(gray_image[i, j])
#         pseudo_color_image[i, j, 0] = GetR(gray)
#         pseudo_color_image[i, j, 1] = GetG(gray)
#         pseudo_color_image[i, j, 2] = GetB(gray)

# # 显示原始灰度图像和伪彩色图像
# plt.figure(figsize=(10, 5))

# plt.subplot(1, 2, 1)
# plt.title("Original Gray Image")
# plt.imshow(gray_image, cmap='gray')
# plt.axis('off')

# plt.subplot(1, 2, 2)
# plt.title("Pseudo Color Image")
# plt.imshow(pseudo_color_image)
# plt.axis('off')

# plt.show()
################
# from skimage import io, color, util, filters, morphology
# import numpy as np
# import matplotlib.pyplot as plt

# # 1. 读取图像并转换为灰度图像
# image = io.imread('lena.bmp')
# gray_image = color.rgb2gray(image) if len(image.shape) == 3 else image

# # 2. 添加高斯加性噪声
# noisy_image = util.random_noise(gray_image, mode='gaussian', mean=0, var=0.01)

# # 3. 应用盒状滤波器（均值滤波）
# # 使用正确的参数名 'footprint' 而不是 'selem'
# box_filtered_image = filters.rank.mean(util.img_as_ubyte(noisy_image), footprint=morphology.disk(2))

# # 4. 应用高斯滤波器（加权平均滤波）
# gaussian_filtered_image = filters.gaussian(noisy_image, sigma=1)

# # 5. 显示原始、加噪后以及两种去噪的结果图像
# plt.figure(figsize=(18, 6))

# plt.subplot(1, 4, 1)
# plt.title('Original Gray Image')
# plt.imshow(gray_image, cmap='gray')
# plt.axis('off')

# plt.subplot(1, 4, 2)
# plt.title('Noisy Image')
# plt.imshow(noisy_image, cmap='gray')
# plt.axis('off')

# plt.subplot(1, 4, 3)
# plt.title('Box Filtered Image')
# plt.imshow(box_filtered_image, cmap='gray')
# plt.axis('off')

# plt.subplot(1, 4, 4)
# plt.title('Gaussian Filtered Image')
# plt.imshow(gaussian_filtered_image, cmap='gray')
# plt.axis('off')

# plt.tight_layout()
# plt.show()
# from skimage import io, color, util
# import numpy as np
# import matplotlib.pyplot as plt

# # 定义巴特沃斯低通滤波器
# def butterworth_lowpass(img, cutoff, order=2):
#     # 获取图像尺寸
#     rows, cols = img.shape
#     crow, ccol = rows // 2, cols // 2
    
#     # 创建频率网格
#     x, y = np.ogrid[:rows, :cols]
#     distance = ((x - crow)**2 + (y - ccol)**2)**0.5
    
#     # 创建巴特沃斯低通滤波器
#     H = 1 / (1 + (distance / cutoff)**(2*order))
    
#     # 将图像转换到频域
#     f = np.fft.fft2(img)
#     fshift = np.fft.fftshift(f)
    
#     # 应用滤波器
#     fshift_filtered = fshift * H
    
#     # 反变换回空间域
#     f_ishift = np.fft.ifftshift(fshift_filtered)
#     img_back = np.abs(np.fft.ifft2(f_ishift))
    
#     return img_back

# # 读取并转换为灰度图像
# image = io.imread('lena.bmp')
# gray_image = color.rgb2gray(image) if len(image.shape) == 3 else image

# # 添加高斯噪声
# noisy_image = util.random_noise(gray_image, mode='gaussian', mean=0, var=0.01)

# # 使用巴特沃斯低通滤波器进行去噪
# butterworth_filtered_image = butterworth_lowpass(noisy_image, cutoff=30, order=2)

# # 显示原始、加噪后以及巴特沃斯滤波器去噪的结果图像
# plt.figure(figsize=(18, 6))

# plt.subplot(1, 3, 1)
# plt.title('Original Gray Image')
# plt.imshow(gray_image, cmap='gray')
# plt.axis('off')

# plt.subplot(1, 3, 2)
# plt.title('Noisy Image')
# plt.imshow(noisy_image, cmap='gray')
# plt.axis('off')

# plt.subplot(1, 3, 3)
# plt.title('Butterworth Filtered Image')
# plt.imshow(butterworth_filtered_image, cmap='gray')
# plt.axis('off')

# plt.tight_layout()
# plt.show()
#############
# from skimage import io, color, util, filters, morphology
# import numpy as np
# import matplotlib.pyplot as plt

# # 1. 读取图像并转换为灰度图像
# image = io.imread('lena.bmp')
# gray_image = color.rgb2gray(image) if len(image.shape) == 3 else image

# # 2. 添加椒盐噪声
# noisy_image = util.random_noise(gray_image, mode='s&p', amount=0.05)

# # 3. 使用中值滤波器进行去噪
# median_filtered_image = filters.median(noisy_image, footprint=morphology.square(3))

# # 4. 显示原始、加噪后以及中值滤波器去噪的结果图像
# plt.figure(figsize=(18, 6))

# plt.subplot(1, 3, 1)
# plt.title('Original Gray Image')
# plt.imshow(gray_image, cmap='gray')
# plt.axis('off')

# plt.subplot(1, 3, 2)
# plt.title('Noisy Image (Salt & Pepper)')
# plt.imshow(noisy_image, cmap='gray')
# plt.axis('off')

# plt.subplot(1, 3, 3)
# plt.title('Median Filtered Image')
# plt.imshow(median_filtered_image, cmap='gray')
# plt.axis('off')

# plt.tight_layout()
# plt.show()
#############
import numpy as np
from skimage import io, color, filters, img_as_float
import matplotlib.pyplot as plt

# 1. 读入图像并查看其数组形状和类型

image = io.imread(r'c:\Users\HP\Desktop\python\source.JPG')
print("Original image shape:", image.shape)

# 确认图像是否为灰度图像（即只有两个维度）
is_gray = len(image.shape) == 2 or (len(image.shape) == 3 and image.shape[2] == 1)

# 2. 如果不是灰度图像，则转换为灰度图像
if not is_gray:
    gray_image = color.rgb2gray(image)
else:
    # 如果已经是灰度图像，则直接使用
    gray_image = img_as_float(image) if image.dtype != np.float64 else image

# 确保灰度图像是浮点数格式，以便后续操作
gray_image = img_as_float(gray_image)

# 3. 使用不同的边缘检测算子进行边缘检测
edges_roberts = filters.roberts(gray_image)
edges_sobel = filters.sobel(gray_image)
edges_laplace = filters.laplace(gray_image)

# 对于LoG算子，首先应用高斯模糊，然后应用Laplace算子
edges_log_blur = filters.gaussian(gray_image, sigma=1)  # 首先应用高斯模糊
edges_log = filters.laplace(edges_log_blur)  # 然后应用Laplace算子

# 显示结果
plt.figure(figsize=(15, 10))

plt.subplot(2, 2, 1)
plt.title('Roberts Edge Detection')
plt.imshow(edges_roberts, cmap='gray')
plt.axis('off')

plt.subplot(2, 2, 2)
plt.title('Sobel Edge Detection')
plt.imshow(edges_sobel, cmap='gray')
plt.axis('off')

plt.subplot(2, 2, 3)
plt.title('Laplace Edge Detection')
plt.imshow(edges_laplace, cmap='gray')
plt.axis('off')

plt.subplot(2, 2, 4)
plt.title('LoG Edge Detection')
plt.imshow(edges_log, cmap='gray')
plt.axis('off')

plt.tight_layout()
plt.show()